using System;
using CGF;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;

public class Dropdown : MonoBehaviour
{
    public RectTransform rectTransform { get { return transform as RectTransform; } }
    private Action<int> _onSelect;
    public int currIndex { get; private set; }

    public CButton[] cells;
    
    void Awake()
    {
        ResetCellsAction();
        gameObject.SetActive(false);
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (TouchHelper.IsTouchOnUI(gameObject, Input.mousePosition))
            {
                return;
            }
            Hide();
        }
    }
    
    public void ResetCells(CButton[] cells)
    {
        this.cells = cells;
        ResetCellsAction();
    }

    public void ResetCellsAction()
    {
        for (int i = 0; i < cells.Length; i++)
        {
            int index = i;
            cells[i].triggerInterval = 0.25f;
            cells[i].SetClick(() =>
            {
                currIndex = index;
                _onSelect?.Invoke(index);
                Hide();
            });
        }
    }

    public void SetOnSelect(Action<int> onSelect)
    {
        _onSelect = onSelect;
    }

    public void InvokeSelect(int index)
    {
        currIndex = index;
        _onSelect?.Invoke(index);
    }

    public void Show()
    {
        gameObject.SetActive(true);
        transform.localScale = new Vector3(1, 0.75f, 1);
        transform.DOScaleY(1, 0.25f).SetEase(Ease.OutBack);
    }

    public void Hide()
    {
        transform.DOScaleY(0f, 0.1f).SetEase(Ease.Linear).OnComplete(() =>
        {
            gameObject.SetActive(false);
        });
    }

    public Sprite GetIcon(int index)
    {
        return cells[index].gameObject.Get<Image>("Icon").sprite;
    }
    
    public string GetText(int index)
    {
        return cells[index].gameObject.Get<Text>("Text").text;
    }
}
